package com.qiche.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.qiche.config.YmlConfig;
import com.qiche.util.FastDFSUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.qiche.aspect.Result;
import com.qiche.dto.MerchantLngLatDto;
import com.qiche.enums.ResultEnum;
import com.qiche.model.Agent;
import com.qiche.model.Merchant;
import com.qiche.model.SpecialOffer;
import com.qiche.model.StoreMember;
import com.qiche.qrcode.QRCodeUtils;
import com.qiche.service.AgentService;
import com.qiche.service.MerchantService;
import com.qiche.service.SpecialOfferService;
import com.qiche.service.StoreMemberService;
import com.qiche.util.ApiUtils;
import com.qiche.util.Sign;
import com.vdurmont.emoji.EmojiParser;

/**
 * @author LB
 *
 * @date 2018年5月26日
 */
@RestController
@RequestMapping(value = "wx/user")
public class WxUserAccreditController {

	private static final Logger log = LoggerFactory.getLogger(WxUserAccreditController.class);

	@Autowired
	private MerchantService merchantService;

	@Autowired
	private StoreMemberService storeMemberService;

	@Autowired
	private AgentService agentService;

	@Autowired
	private SpecialOfferService specialOfferService;

	@Autowired
	private YmlConfig ymlConfig;

	/**
	 * 返回APPID
	 * 
	 * @param officialAccount
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/getAPPID")
	public Result<?> getAPPID(@RequestParam String officialAccount) throws Exception {
		Merchant merchant = merchantService.selectByOfficialAccount(officialAccount);
		Agent agent = agentService.selectByOfficialAccount(officialAccount);
		if (merchant == null && agent == null) {
			return Result.createByErrorMessage("你的公众号：" + officialAccount + "不对，走点心大哥！");
		}
		Map<String, Object> map = new HashMap<>();
		map.put("appid", merchant != null ? merchant.getAppid() : agent.getAppid());
		return Result.createBySuccess(map);
	}

	/**
	 * 微信授权
	 * 
	 * @param code
	 * @param officialAccount
	 * @return
	 */
	@SuppressWarnings("unused")
	@PostMapping("/accredit")
	public Result<?> accredit(@RequestParam String code, @RequestParam String officialAccount) {
		try {
			Merchant merchant = merchantService.selectByOfficialAccount(officialAccount);
			// 请求参数
			if (merchant == null ) {
				return Result.createByErrorMessage("用户数据异常");
			}
			// token可以放一下缓存
			JSONObject json = ApiUtils.wxAccessToken(merchant.getAppid(), merchant.getAppSecret(), code);
			if (StringUtils.isEmpty(json.getString("access_token")) || ("40163").equals(json.getString("errcode"))) {
				return Result.createByErrorMessage("请检查code获取不到access_token");
			}
			log.info("access_token:{}", json.getString("access_token"));
			JSONObject userinfoJson = ApiUtils.wxUserinfo(json.getString("access_token"), json.getString("openid"));
			log.info("微信返回信息:{}", userinfoJson);
			StoreMember storeMember;
			if (StringUtils.isEmpty(userinfoJson.getString("unionid"))) {
				storeMember = storeMemberService.selectByOpenidMerchantid(userinfoJson.getString("openid"),
						merchant.getId());
			} else {
				storeMember = storeMemberService.selectByOpenidUnionidMerchantid(userinfoJson.getString("openid"),
						userinfoJson.getString("unionid"), merchant.getId());
			}
			if (storeMember == null) {
				storeMember = new StoreMember();
				storeMember.setUnionid(userinfoJson.getString("unionid"));
				storeMember.setOpenid(userinfoJson.getString("openid"));
				storeMember.setNickname(EmojiParser.removeAllEmojis(userinfoJson.getString("nickname")));
				storeMember.setAvatar(userinfoJson.getString("headimgurl"));
				storeMember.setMerchantId(merchant.getId());
				storeMember.setCreateTime(new Date());
				storeMember.setConsumeCount(0);
				storeMember.setConsumeMoney(new BigDecimal(0));
				storeMemberService.save(storeMember);
			}
			// 构造签名键值对的格式
			StringBuilder sb = new StringBuilder();
			if (StringUtils.isNotEmpty(userinfoJson.getString("unionid"))) {
				sb.append(userinfoJson.getString("unionid"));
			}
			sb.append(userinfoJson.getString("openid"));
			sb.append(ymlConfig.getAccessTokenKey());
			// 进行MD5加密
			String result = DigestUtils.md5Hex(sb.toString()).toUpperCase();
			Map<String, Object> resulMap = new HashMap<>();
			resulMap.put("accessToken", result);
			resulMap.put("merchantId", merchant.getId());
			resulMap.put("merchantPhone", merchant.getPhone());
			resulMap.put("merchantName", merchant.getName());
			resulMap.put("agentId", merchant.getAgentId());
			resulMap.put("unionid", storeMember.getUnionid());
			resulMap.put("openid", storeMember.getOpenid());
			resulMap.put("headimgurl", storeMember.getAvatar());
			resulMap.put("nickname", storeMember.getNickname());
			if (StringUtils.isEmpty(storeMember.getPhone())) {
				return Result.createByResultEnum(ResultEnum.RETRUN_REGISTER_PAGE, resulMap);
			}
			return Result.createBySuccess("微信授权成功", resulMap);
		} catch (Exception e) {
			log.info("微信登录异常:{}", e);
			return Result.createByErrorMessage("微信授权失败");
		}
	}

	/**
	 * 微信特价
	 * 
	 * @param merchantId
	 * @return
	 */
	@PostMapping(value = "/specialOffer")
	public Result<?> specialOffer(String merchantId) {
		SpecialOffer specialOffer = specialOfferService.selectByMerchantId(Integer.valueOf(merchantId));
		return Result.createBySuccess(specialOffer);
	}

	/**
	 * 商家经纬度获取
	 * 
	 * @param merchantId
	 * @return
	 */
	@PostMapping(value = "/LongitudeAndLatitude")
	public Result<?> merchantLongitudeAndLatitude(@RequestParam String url, @RequestParam Integer merchantId) {
		try {
			Merchant merchant = merchantService.selectByKey(merchantId);
			if (StringUtils.isEmpty(merchant.getAppid())) {
				return Result.createByErrorMessage("appid都为空，请先在后台添加商户信息！");
			}
			JSONObject json = ApiUtils.wxAccessToken(merchant);

			if (StringUtils.isEmpty(json.getString("access_token")) || ("40163").equals(json.getString("errcode"))) {
				log.error("access_token获取异常请检查code:{}", json.getString("errmsg"));
				return Result.createByErrorMessage("access_token获取异常请" + json.getString("errmsg"));
			}
			JSONObject jsapiTicketJson = ApiUtils.wxJsapiTicket(json.getString("access_token"));

			Map<String, String> map = Sign.sign(url, jsapiTicketJson.getString("ticket"));

			MerchantLngLatDto merchantLngLatDto = new MerchantLngLatDto();
			merchantLngLatDto.setAddress(merchant.getAddress());
			merchantLngLatDto.setLat(merchant.getLat());
			merchantLngLatDto.setLng(merchant.getLng());
			merchantLngLatDto.setName(merchant.getName());
			map.put("appid", merchant.getAppid());
			merchantLngLatDto.setMap(map);
			return Result.createBySuccess("商家经纬度查询成功", merchantLngLatDto);
		} catch (Exception e) {
			log.info("获取经纬度异常:{}", e);
			return Result.createByErrorMessage("获取经纬度异常");
		}

	}

	/**
	 * 根据卡号 获取卡券二维码
	 *
	 * @param response
	 */
//	@PostMapping(value = "/getQrCode")
//	public void getCardCodeImg(@RequestParam("cardCode") String cardCode, HttpServletResponse response) {
//		try {
//			if (cardCode != null && !"".equals(cardCode)) {
//				ServletOutputStream stream = null;
//				stream = response.getOutputStream();
//				BitMatrix m = QRCodeUtils.generateQRImage(cardCode, "png");
//				MatrixToImageWriter.writeToStream(m, "png", stream);
//				stream.flush();
//				stream.close();
//			}
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
	@PostMapping(value = "/getQrCode")
	public Result getCardCodeImg(@RequestParam("cardCode") String cardCode, HttpServletResponse response) {
		try {
			File htmlFile = File.createTempFile(cardCode, ".png");//创建临时文件
			if (cardCode != null && !"".equals(cardCode)) {
				BitMatrix m = QRCodeUtils.generateQRImage(cardCode, "png");
				QRCodeUtils.writeToFile(m, "png", htmlFile);
				String paths = FastDFSUtils.uploadFilePic(htmlFile);
				htmlFile.deleteOnExit();
				return Result.createByResultEnum(ResultEnum.SUCCESS, ymlConfig.getFastdfsDomainUrl() + paths);
			}
		}  catch (Exception e) {
			e.printStackTrace();
		}
		return Result.createByErrorMessage("回显错误");
	}
}
